package beans;

import user.UserAdminManagedBean;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ValueChangeEvent;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

/**
 * The RegBean is used to handle and process all User Inputs during a Registration.
 * The dedicated site is reg.xhtml
 * 
 * @author Thorsten Ludwig
 */
@ManagedBean(name="regBean")
@RequestScoped
public class RegistrationManagedBean {

    @Resource(name = "mail/cismail")
    private Session mailSession;
        
    /**
     * entered first name
     */
    private String firstName;
    /**
     * entered last name
     */
    private String lastName;
    /**
     * the created username.
     * the username is created by the mail adress.
     * only the part before the '@' is used, for example:
     * 'mail@server.com' will be 'mail'
     */
    private String username;
    /**
     * entered studentID
     */
    private String studentID;

    /**
     * entered mail adress.
     */
    private String mail;
    /**
     * is the mail adress already used?
     */
    private boolean mailUsed;
    
    private boolean wrongMail;
    /**
     * selected study course
     */
    private String studyCourse;
    
    private String aspiredDegree;
    
    private List<String> courses;

    /**
     * create an empty Registration Bean
     */
    public RegistrationManagedBean() {
        this.courses = this.generateCourses();        
    }

    /**
     * cut of everything after the '@'
     * @param e the new username
     */
    public void makeUsernameByMail (ValueChangeEvent e) {
        String s = (String) e.getNewValue();
        this.username = s.split("@", 2)[0];
        System.out.println("Neuer Username generiert aus Mailadresse " + e.getNewValue());
        System.out.println("Lautet jetzt " + this.username);
    }

    /**
     * Try to create the User
     * @return if the creation was succesful, the start page is returned
     *         else an empty string is returned
     */
    public String doRegistration() {
        FacesContext c = FacesContext.getCurrentInstance();
        UserAdminManagedBean userAdmin = c.getApplication().evaluateExpressionGet(c, "#{userAdminBean}", UserAdminManagedBean.class);
        boolean uniMail = this.mail.contains("@student.uni-tuebingen.de")
                || this.mail.contains("@informatik.uni-tuebingen.de")
                || this.mail.contains("@uni-tuebingen.de");
        if (userAdmin.isMailUsed(this.mail)) {
            this.mailUsed = true;
            return "";
        } else if (!uniMail) {
            this.wrongMail = true;
            return "";
        } else {
            String password = this.generatePassword();
            System.out.println(this.firstName);
            System.out.println(this.lastName);
            System.out.println(this.username);
            System.out.println(this.studentID);
            System.out.println(password);
            System.out.println(this.mail);
            System.out.println(this.aspiredDegree);
            userAdmin.createUsers(this.firstName, 
                                  this.lastName, 
                                  this.username,
                                  password,
                                  this.mail,
                                  this.studentID,
                                  this.aspiredDegree,
                                  this.studyCourse);
            this.sendMail(this.mail, password);
            return "index.jsf";
        }

    }
    
    /**
     * Return the entered Username
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * set a new Username
     * @param username the new Username
     */
    public void setUsername(String username) {
    }

    /**
     * Return the entered first Name
     * @return entered first name
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * set a new first name
     * @param firstName the new first name
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * get the entered last name
     * @return entered last name
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * set a new last name
     * @param lastName the new last name
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * return the entered mail adress
     * @return the entered mail adress
     */
    public String getMail() {
        return mail;
    }

    /**
     * set a new mail adress
     * @param mail the new mail adress
     */
    public void setMail(String mail) {
        this.mail = mail;
    }

    /**
     * get the entered student ID
     * @return
     */
    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getStudiengang() {
        return studyCourse;
    }

    public void setStudiengang(String studiengang) {
        this.studyCourse = studiengang;
    }

    public boolean isMailVergeben() {
        return mailUsed;
    }

    /**
     * generateCourses Create a List of avaible Courses at the University of Tübingen.
     * TODO: Add all avaible Courses
     * @return List of all avaible courses
     */
    private List<String> generateCourses() {
        List<String> list = new ArrayList<String>();
        list.add("Informatik");
        list.add("Bioinformatik");
        list.add("Medieninformatik");
        list.add("Kognitionswissenschaft");
        list.add("Mathematik");
        list.add("Physik");
        list.add("Psychologie");
        list.add("Philosophie");
        
        return list;
    }
    
    public List<String> generateDegrees() {
        List<String> list = new ArrayList<String>();
        list.add("Bachelor");
        list.add("Master");
        list.add("Diplom");
        list.add("Magister");
        list.add("Lehramt");
        
        return list;
    }

    public List<String> getCourses() {
        return courses;
    }

    public String getAspiredDegree() {
        return aspiredDegree;
    }

    public void setAspiredDegree(String aspiredDegree) {
        this.aspiredDegree = aspiredDegree;
    }

    private String generatePassword() {
        Random r = new Random();
        String pw="";
        int asc ;
        for (int i=0;i<12;i++) {
            asc = r.nextInt(25);
            pw = pw + (char) (asc+97);
        }
        return pw;
    }
    
    public void sendMail(String to, String pw) {
        Message msg = new MimeMessage(mailSession);
        try {
          
          msg.setRecipient(RecipientType.TO, new InternetAddress(to));
          msg.setSubject("Ihr Passwort für CIS 3");          
          String message = "Vielen Dank für ihre Registrierung. Ihr Passwort lautet " + pw;
          message = message + "\n Bitte ändern sie es umgehend.\n";
          msg.setText(message);
          Transport.send(msg);
          System.out.println("E-Mail gesendet");
        }
        catch(MessagingException me) {
          // manage exception
            me.printStackTrace();
        }
    }

    public boolean isWrongMail() {
        return wrongMail;
    }

    public void setWrongMail(boolean wrongMail) {
        this.wrongMail = wrongMail;
    }
}